'use strict';
const assert = require('assert');
module.exports = {
  /**
   * 登录操作
   * @param {String} loginCase 单个登录的名称
   */
  login(loginCase) {
    assert(loginCase, 'loginCase required');
    try {
      const { [loginCase]: { appId, redirectUri }, serverHost } = this.app.config.zconnect;
      const state = '123';
      const url = `${serverHost}/authorize?scope=openid&state=${state}&response_type=code&client_id=${appId}&redirect_uri=${encodeURIComponent(redirectUri)}`;
      this.logger.debug(`[zconnectLogin] login() redirect url: ${url}`);
      this.session[loginCase] = { state };
      this.redirect(url);
    } catch (error) {
      this.logger.error(`[zonnectLogin] 登录失败 err: ${error}`);
      this.body = '';
      delete this.session[loginCase];
    }
  },
  /**
   * 登出
   * @param {String} loginCase 单个登录的名称
   */
  async logout(loginCase) {
    assert(loginCase, 'loginCase required');
    const { serverHost } = this.app.config.zconnect;
    const url = `${serverHost}/oidc/logout`;
    try {
      const { sub: lid, access_token } = this.session[loginCase];
      const res = (await this.curl(url, {
        data: {
          lid,
          accessToken: access_token,
        },
        dataType: 'json',
      })).data;
      if (res.result !== 0) {
        this.logger.warn(`[zonnectLogin] 退出登录不成功, ${res.msg}`);
      }
    } catch (err) {
      this.logger.error(`[zonnectLogin] 退出登录异常 err:  ${err}`);
    }
    delete this.session[loginCase];
  },
  /**
   * 判断是否是登录
   * @param {String} loginCase 单个登录的名称
   * @return {Boolean} 是否是登录
   */
  isLogin(loginCase) {
    assert(loginCase, 'loginCase required');
    return this.session[loginCase] ? this.session[loginCase].access_token : false;
  },
  /**
   * 获取用户数据
   * @param {String} loginCase 单个登录的名称
   * @return {Object} 用户登录数据
   */
  getUserInfo(loginCase) {
    assert(loginCase, 'loginCase required');
    return this.session[loginCase] || {};
  },
};
